//
//  UIView+Function.swift
//  UIView 扩展
//
//  Created by mini on 2025/4/28.
//

import Foundation
import UIKit

extension UIView {
    
    // MARK: - 获取所在vc
    func fetchVC() -> UIViewController? {
        var responder: UIResponder? = self
        while let nextResponder = responder?.next {
            if let viewController = nextResponder as? UIViewController {
                return viewController
            }
            responder = nextResponder
        }
        return nil
    }
    
    // MARK: - 组合views
    class func initWithViews(_ ary: [UIView]?) -> UIView {
        let viewReturn = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0))
        viewReturn.backgroundColor = .clear
        if let views = ary {
            var top: CGFloat = 0
            for view in views {
                if view.height>0  {
                    viewReturn.addSubview(view)
                    if let bgColor = view.topToUpViewBGColor {
                        let lineView = UIView(frame: CGRect(x: 0, y: top, width: view.frame.width, height: view.topToUpView))
                            lineView.backgroundColor = bgColor
                            viewReturn.addSubview(lineView)
                    }
                    view.top = top+view.topToUpView
                    top = view.bottom
                }
            }
            viewReturn.height = top
        }
        return viewReturn
    }
    
    // MARK: - 移除全部试图
    func removeAllSubviews() {
        while self.subviews.count > 0 {
            self.subviews.last?.removeFromSuperview()
        }
    }
    
    // MARK: - 添加点击响应的动画
    func addClickAnimate(_ scale: Double = 0.9) {
        UIView.animate(withDuration: 0.16, animations: {
            self.transform = CGAffineTransform(scaleX: scale, y: scale)
        }, completion: { _ in
            UIView.animate(withDuration: 0.16) {
                self.transform = CGAffineTransform.identity
            }
        })
    }
    
    // MARK: - 转为Image
    public func toImage() -> UIImage? {
        let size = bounds.size
        // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数。
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }
        layer.render(in: context)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
